package com.yootk.config;

import com.yootk.task.DynamicCronExpression;
import com.yootk.task.ShedLockTask2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

/**
 * 动态配置类
 */
@Slf4j
//@Configuration
public class DynamicScheduleConfig implements SchedulingConfigurer {

    @Autowired
    private DynamicCronExpression cronExpression;

    @Autowired
    private ShedLockTask2 scheduleTask;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(   // 添加任务内容
                () -> scheduleTask.task(),
                triggerContext -> {     // 设置任务触发表达式
                    log.info("设置当前的CRON表达式：{}", cronExpression.getCron());
                    String cron = cronExpression.getCron();     // 获取执行周期
                    return new CronTrigger(cron)
                            .nextExecutionTime(triggerContext); // 添加新的触发器
                });
    }
}
